package com.zdp.item.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zdp.common.constant.RedisConstants;
import com.zdp.common.domain.Items;
import com.zdp.common.utils.JsonUtils;
import com.zdp.common.utils.RedisOperator;
import com.zdp.item.mapper.ItemsMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author sesshomaru
 * @date 2021/7/10 14:25
 */
@Service
public class ItemService {

    @Autowired
    private ItemsMapper itemsMapper;

    @Autowired
    private RedisOperator redis;

    // 查询所有商品大类
    public Items findItemList(String itemId) {
        return findItemById(itemId);
    }

    public Items findItemById(String itemId) {
        String key = String.format(RedisConstants.CACHE_ITEM_KEY, itemId);
        String itemCacheJson = redis.get(key);
        if (StringUtils.isBlank(itemCacheJson)) {
            Items item = itemsMapper.selectById(itemId);
            if (Optional.ofNullable(item).isPresent()) {
                redis.set(key, JsonUtils.objectToJson(item), 2, TimeUnit.DAYS);
                // 如果数据库不存在该数据则保存空对象，避免缓存穿透
            } else {
                redis.set(key, JsonUtils.objectToJson(item), 10, TimeUnit.SECONDS);
            }
            return item;
        } else {
            return JsonUtils.jsonToPojo(itemCacheJson, Items.class);
        }
    }

}
